package com.deercrowing.takeaway.controller.user;

import com.alibaba.fastjson.JSON;
import com.deercrowing.takeaway.common.exception.BusinessException;
import com.deercrowing.takeaway.common.model.Result;
import com.deercrowing.takeaway.service.DishesService;
import com.deercrowing.takeaway.vo.DishesVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Slf4j
@Validated
@RestController
@RequestMapping("user/dishes")
public class DishesWithUserController {

    @Autowired
    DishesService dishesService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 获取该分类下菜品信息
     *
     */
    @GetMapping("/list")
    public ResponseEntity dishesType(@RequestParam Short categoryId){
        log.info("传入分类:{}",categoryId);

        if (Objects.isNull(categoryId)){
            throw new BusinessException("传入分类为空");
        }

        String key = "dish_" + categoryId;
        List<String> tmpList = (List<String>) redisTemplate.opsForList().range(key,0,-1);
        List<DishesVO> dishesVOList = new ArrayList<>();

        for (String tmp : tmpList){
            dishesVOList.add(JSON.parseObject(tmp,DishesVO.class));
        }

        if (dishesVOList != null && dishesVOList.size() > 0 && !ObjectUtils.isEmpty(dishesVOList)){
            return ResponseEntity.ok(Result.OK(dishesVOList));
        }

        dishesVOList = this.dishesService.selectDishWithFlavor(categoryId);
        for(DishesVO dishesVO : dishesVOList) {
            this.redisTemplate.opsForList().leftPush(key, JSON.toJSON(dishesVO).toString());
        }

        Collections.sort(dishesVOList,Comparator.comparingInt(DishesVO::getId).reversed());

        return ResponseEntity.ok(Result.OK(dishesVOList));
    }
}
